package com.ciaojian.client.policy.impl.product;

import cn.hutool.core.date.DateField;
import com.ciaojian.client.service.TimesCardServiceImpl;
import com.ciaojian.core.mapper.UserTimesCardMapper;
import com.ciaojian.core.model.TimesCard;
import com.ciaojian.core.model.User;
import com.ciaojian.core.model.UserTimesCard;
import com.ciaojian.core.service.ProductHandleService;
import com.ciaojian.core.service.UserTimesCardService;
import com.ciaojian.core.util.ApplicationContextHelper;
import com.ciaojian.core.util.DateUtil;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author oxiny
 */
@Service
public class TimesCardHandleServiceImpl implements ProductHandleService {
    private final UserTimesCardService<UserTimesCardMapper, UserTimesCard> userTimesCardService = ApplicationContextHelper.getBean(UserTimesCardService.class);
    private final TimesCardServiceImpl timesCardService = ApplicationContextHelper.getBean(TimesCardServiceImpl.class);

    @Override
    public void checkLimit(User user, Integer productId) {
        // 查询用户的次卡信息
        Optional<UserTimesCard> optional = userTimesCardService.getByUserIdAndCardId(user.getId(), productId);
        // 如果用户已有次卡, 查询是否可以叠加
        optional.ifPresent((userTimesCard) -> {
            TimesCard timesCard = timesCardService.getById(productId);
            // 不可重复购买
            if (!timesCard.getOverlay()) {
                return;
            }
            // 叠加次卡时长
            if (timesCard.getExpiredType().compareTo(0) == 0) {
                DateUtil.offset(userTimesCard.getDueDate(), DateField.DAY_OF_YEAR, timesCard.getDay());
                userTimesCard.updateById();
            }
        });
    }
}
